import { In, Repository, Like, Between, Not } from 'typeorm';
import { AppDataSource } from '../../config/database';
import { SystemMessage, MessageStatus, MessageType } from '../../entities/SystemMessage';
import { User } from '../../entities/User';

export class MessageService {
  private messageRepository: Repository<SystemMessage>;
  private userRepository: Repository<User>;

  constructor() {
    this.messageRepository = AppDataSource.getRepository(SystemMessage);
    this.userRepository = AppDataSource.getRepository(User);
  }

  /**
   * 获取消息列表（管理员接口）
   */
  async getUserMessages(query: any = {}): Promise<{ messages: SystemMessage[]; total: number }> {
    const { page = 1, pageSize = 10, status, type, userId } = query;
    
    const queryBuilder = this.messageRepository.createQueryBuilder('msg')
      .leftJoinAndSelect('users', 'user', 'user.id = msg.userId')
      .select([
        'msg.*',
        'user.id as userIdFrom',
        'user.name as userNameFrom',
        'user.avatar as userAvatarFrom'
      ]);
    
    // 如果传入了用户ID，则按用户ID筛选
    if (userId) {
      queryBuilder.andWhere('msg.userId = :userId', { userId });
    }
    
    // 添加状态过滤
    if (status !== undefined) {
      queryBuilder.andWhere('msg.status = :status', { status });
    } else {
      // 默认只显示未删除的消息
      queryBuilder.andWhere('msg.status <> :deletedStatus', { deletedStatus: MessageStatus.DELETED });
    }
    
    // 添加类型过滤
    if (type !== undefined) {
      queryBuilder.andWhere('msg.type = :type', { type });
    }
    
    // 排序：未读在前，时间倒序
    queryBuilder.orderBy('msg.status', 'ASC')
      .addOrderBy('msg.createTime', 'DESC');
    
    // 分页
    const total = await queryBuilder.getCount();
    const messages = await queryBuilder
      .offset((page - 1) * pageSize)
      .limit(pageSize)
      .getRawMany();
    
    // 格式化返回数据
    const formattedMessages = messages.map(msg => ({
      ...msg,
      user: {
        id: msg.userIdFrom,
        name: msg.userNameFrom,
        avatar: msg.userAvatarFrom
      }
    }));

    return { 
      messages: formattedMessages, 
      total 
    };
  }

  /**
   * 获取消息详情
   */
  async getMessageById(id: string): Promise<any> {
    const message = await this.messageRepository.createQueryBuilder('msg')
      .leftJoinAndSelect('users', 'user', 'user.id = msg.userId')
      .select([
        'msg.*',
        'user.id as userIdFrom',
        'user.name as userNameFrom',
        'user.avatar as userAvatarFrom'
      ])
      .where('msg.id = :id', { id })
      .getRawOne();

    if (!message) return null;

    return {
      ...message,
      user: {
        id: message.userIdFrom,
        name: message.userNameFrom,
        avatar: message.userAvatarFrom
      }
    };
  }
  
  /**
   * 标记消息为已读
   */
  async markAsRead(id: string): Promise<boolean> {
    const message = await this.getMessageById(id);
    if (!message || message.status === MessageStatus.DELETED) {
      return false;
    }
    
    message.status = MessageStatus.READ;
    message.updateTime = new Date();
    
    await this.messageRepository.save(message);
    return true;
  }
  
  /**
   * 标记用户所有消息为已读
   */
  async markAllAsRead(userId: string): Promise<boolean> {
    try {
      await this.messageRepository.update(
        { userId, status: MessageStatus.UNREAD },
        { status: MessageStatus.READ, updateTime: new Date() }
      );
      return true;
    } catch (error) {
      console.error('标记所有消息为已读失败:', error);
      return false;
    }
  }
  
  /**
   * 删除消息（标记为已删除）
   */
  async deleteMessage(id: string): Promise<boolean> {
    const message = await this.messageRepository.findOne({ 
      where: { id } 
    });
    
    if (!message) {
      return false;
    }
    
    message.status = MessageStatus.DELETED;
    message.updateTime = new Date();
    
    await this.messageRepository.save(message);
    return true;
  }
  
  /**
   * 批量删除消息
   */
  async batchDeleteMessages(ids: string[]): Promise<number> {
    try {
      const result = await this.messageRepository.update(
        { id: In(ids) },
        { status: MessageStatus.DELETED, updateTime: new Date() }
      );
      
      return result.affected || 0;
    } catch (error) {
      console.error('批量删除消息失败:', error);
      return 0;
    }
  }
  
  /**
   * 获取未读消息数量
   */
  async getUnreadCount(userId: string): Promise<number> {
    return await this.messageRepository.count({
      where: {
        userId,
        status: MessageStatus.UNREAD
      }
    });
  }
}

export const messageService = new MessageService(); 